package sas

import (
	"fmt"
	"strings"
	"time"

	"github.com/micro-plat/lib4go/security/rsa"
	"github.com/micro-plat/lib4go/types"
)

//RSASign 生成签名，chain为参数间连接符，kv为键值间连接符
func (n *sasClient) RSASign(input types.XMap, privateKey, pkcsType string, hasMode ...string) (sign string, data types.XMap, err error) {

	input.SetValue(n.getTimespanName(), time.Now().Format("20060102150405"))
	input.SetValue(n.getEUIDName(), n.euid)
	raw := n.buildRaw(input, privateKey, RSAStr)
	has := types.GetStringByIndex(hasMode, 0, "md5")
	sign, err = rsa.Sign(raw, privateKey, has, pkcsType)
	if err != nil {
		err = fmt.Errorf("RSASign 签名异常,err:%+v", err)
		return
	}
	input[n.getSignName()] = sign
	data = input
	return
}

//RSADecrypt 解密数据
func (n *sasClient) RSADecrypt(input types.XMap, privateKey, pkcsType string) (data types.XMap, err error) {
	//如果没有需要加解密的字段  直接返回原来的
	data = input
	if len(n.encryptName) == 0 {
		return
	}

	pkcsType = strings.ToUpper(pkcsType)
	for _, v := range n.encryptName {
		if input.Has(v) && input.GetString(v) != "" {
			strRes, err := rsa.Decrypt(input.GetString(v), privateKey, pkcsType)
			if err != nil {
				return nil, err
			}
			data.SetValue(v, strRes)
		}
	}

	return
}

//RSAEncrypt 加密数据
func (n *sasClient) RSAEncrypt(input types.XMap) (data types.XMap, err error) {

	//如果没有需要加解密的字段  直接返回原来的
	data = input
	if len(n.encryptName) == 0 {
		return
	}

	//获取密钥
	res, err := n.SecretGet(RSAStr)
	if err != nil {
		return nil, err
	}

	pkcsType := strings.ToUpper(res.PkcsType)
	for _, v := range n.encryptName {
		if input.Has(v) && input.GetString(v) != "" {
			strRes, err := rsa.Encrypt(input.GetString(v), res.RsaPublicSecret, pkcsType)
			if err != nil {
				return nil, err
			}
			data[v] = strRes
		}
	}

	return
}
